package com.chen.interceptor;

import com.chen.bean.constants.WxConstants;
import com.chen.bean.entity.UserEntity;
import com.chen.bean.enums.ResultCode;
import com.chen.exception.BusinessException;
import com.chen.util.JsonMapper;
import com.chen.util.JwtHelper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 微信登录拦截器
 */
@Component
public class WxLoginInterceptor implements HandlerInterceptor {

    private static final ThreadLocal<UserEntity> currentUserInfo = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(WxConstants.WX_LOGIN_TOKEN);
        if (StringUtils.isBlank(token)){
            throw new BusinessException(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage());
        }
        String userInfoJson = JwtHelper.verifyTokenAndGetUserId(token);
        if (StringUtils.isBlank(userInfoJson)){
            throw new BusinessException(ResultCode.AUTHORIZED_ERROR.getCode(),ResultCode.AUTHORIZED_ERROR.getMessage());
        }
        //放入用户信息
        UserEntity userEntity = JsonMapper.fromJson(userInfoJson, UserEntity.class);
        currentUserInfo.set(userEntity);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //每次接口调用完成之后，清除token
        currentUserInfo.remove();
    }

    public static UserEntity getCurrentUser(){
        return currentUserInfo.get();
    }
}
